package com.dlry.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.dlry.entity.DlShare;
import com.dlry.serviceImpl.ShareService;

@Controller
@RequestMapping("/{roler}")
public class ShareController extends BaseController {

	@Autowired
	private ShareService shareService;

	@RequestMapping("/deleteshare")
	public String deleteShare(Long sId, @PathVariable(name = "roler") String roler) {
		shareService.delete(sId);
		return "redirect:/" + roler + "/share";
	}

	@RequestMapping("/newshare")
	public String newShare(Model model, @PathVariable(name = "roler") String roler) {
		DlShare dlShare = new DlShare();
		model.addAttribute("dlShare", dlShare);
		model.addAttribute("roler", roler);
		return "newshare_jsp";
	}

	/**
	 * 
	 * @param dlShare
	 *            需要检验的对象，命名严格按照规则，否则校验失败返回后表单会找不到报错
	 * @param error
	 * @param response
	 * @param roler
	 * @param model
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/saveshare")
	public String saveShare(@Valid DlShare dlShare, Errors error, HttpServletResponse response,
			@PathVariable("roler") String roler, Model model) throws IOException {
		if (error.hasErrors()) {
			return "newshare_jsp";
		}
		shareService.save(dlShare);
		response.reset();
		response.reset();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		PrintWriter writer = response.getWriter();
		writer.println("提交成功，请关闭本页。");
		return null;
	}
}
